<template>
    <div id="Table" >
        <el-container>
            <el-header>
                <!--搜索条件-->
                <search-form v-show="isShow"
                             size='mini'
                             labelWidth = '80px'
                             :toolbarData = "toolbarData"
                             :searchForm = "searchForm"
                             :searchHandle="searchHandle"
                             @on-toolbarData-change="ChangeToolbarData">
                </search-form>
            </el-header>
            <el-main style="height:400px;">
                <el-scrollbar style="height:100%;">
                    <!--Table表格-->
                    <el-table :data="tableData"  border
                              :header-cell-style="{background:'#f5f7fab5',color:'#777'}"
                              @row-dblclick="RowSelect"
                              @selection-change="handleSelectionChange"
                              @current-change="currentChange"
                                ref="table">
                        <el-table-column
                                type="selection"
                                width="55">
                        </el-table-column>
                        <el-table-column v-for="item in tableColumnData"  :key="item.field" :label="item.text" :prop="item.field"  :width="item.width"   :show-overflow-tooltip='true'>
                        </el-table-column>
                    </el-table>
                </el-scrollbar>
            </el-main>
        </el-container>


    </div>
</template>

<script>
    import SearchForm from '../../comm/searchForm.vue';
    import {GetPara} from "../../../api/Gener.js";
    import {DealExp} from "../../../api/tools.js";
    import {FormatDate} from '@/api/tools.js';
    export default {
        name: "Table",
        components:{
            SearchForm,
        },
        props:{
            mapExt:{
                type:Object
            },
            selectRow:{
                type:Array,
                default:()=>[]
            }
        },
        data(){
            return{
                params:{},
                webUser:{},
                isShow:true,
                searchForm:[],
                toolbarData:{},
                searchHandle:[],
                tableData:[],
                tableColumnData:[],
                isDateFrom:false,
                isSameDateFiled:"",
                selectType:true,//默认是多选
                multipleSelection: []

            }
        },
        created(){
            this.params = this.$store.getters.getData;
            this.selectType=GetPara(this.mapExt.AtPara,"SelectType")=="0"?false:true;
            this.SearchBar();
            this.searchHandle.push({label:'查询',type:'primary',handle:()=>this.Search()});
            this.InitTableColumn();
            this.Search();
            this.multipleSelection=this.selectRow;
            this.$nextTick(()=>{
                this.multipleSelection.forEach(row => {
                    this.$refs.table.toggleRowSelection(row,true);
                });
            });

        },
        methods:{
            SearchBar(){
                //需要增加关键字查询
                this.searchForm.push({type:'Input', label:"关键字", prop:"SearchKey", placeholder:GetPara(this.mapExt,"SearchTip"),width:'140px'});
                this.toolbarData.SearchKey="";
                let condtions = this.mapExt.Tag1;
                if(condtions==""){
                    this.isShow = true;
                    return;
                }
                let tempArry = condtions.split("$");
                tempArry.forEach(item=>{
                    if (item == "")
                        return true;
                    if(item.split("#").length!=3)
                        return true;
                    this.CondtionArryPush(item);

                });
            },
            CondtionArryPush(condtion){
                let paras = condtion.split("#");
                let item = {};
                let paraKey = "", labelText = "";
                let ctrType = "Date", ctrValue = "";
                paras.forEach(para=> {
                    if (para.indexOf("Para=") > -1) {
                        paraKey = para.replace("Para=", "");
                    }
                    if (para.indexOf("Label=") > -1) {
                        labelText = para.replace("Label=", "");
                    }
                    if (para.indexOf("ListURL=") > -1) {
                        ctrValue = para.replace("ListURL=", "");
                        ctrType = "ListURL";
                    }
                    if (para.indexOf("ListSQL=") > -1) {
                        ctrValue = para.replace("ListSQL=", "");
                        ctrType = "ListSQL";
                    }
                    if (para.indexOf("ListFuncName=") > -1) {
                        ctrValue = para.replace("ListFuncName=", "");
                        ctrType = "ListFuncName";
                    }
                    if (para.indexOf("EnumKey=") > -1) {
                        ctrValue = para.replace("EnumKey=", "");
                        ctrType = "EnumKey";
                    }
                    if (para.indexOf("DefVal=") > -1) {
                        ctrValue = para.replace("DefVal=", "");
                        if (this.isDateFrom == false) {
                            this.isDateFrom = true;
                            this.isSameDateFiled = paraKey;
                            ctrType = "DateFrom";
                        } else {
                            ctrType = "DateTo";
                            if (paraKey == this.isSameDateFiled)
                                paraKey = paraKey + "_DateTo";
                        }
                    }
                });

                item.CtrlType = ctrType;

                item.FieldKey = paraKey;
                item.Label = labelText;
                item.Val = ctrValue;
                this.CreateCondtionCtrls(item);

            },
            CreateCondtionCtrls(condtion){
                switch (condtion.CtrlType) {
                    case "ListURL":
                    case "ListSQL":
                    case "ListFuncName":
                        var ifcData;
                        if (this.mapExt.DBType == 0 && condtion.CtrlType=="ListSQL") {
                            var en = new this.Entity("BP.Sys.MapExt",this.mapExt);
                            en.MyPK = this.mapExt.MyPK;
                            ifcData = en.DoMethodReturnString("GetDataTableByTag1", condtion.FieldKey, "", this.params.WorkID+"");
                            if (ifcData.indexOf("err@") != -1) {
                                this.$message.error(ifcData);
                                console.log(ifcData);
                                return;
                            }
                            ifcData = JSON.parse(ifcData);
                        } else {
                            let dbSrc = condtion.Val.replace(/~/g, "'");
                            dbSrc = DealExp(dbSrc);
                            ifcData = this.DBAccess.RunDBSrc(dbSrc);
                        }
                        this.searchForm.push( {type:'Select',label:condtion.Label,prop:condtion.FieldKey,width:"120px",options:ifcData,props:{label:'Name',value:'No'}});
                        this.toolbarData[condtion.FieldKey]="";
                        break;
                    case "EnumKey":
                        var enums = new this.Entities("BP.Sys.SysEnums");
                        enums.Retrieve("EnumKey",condtion.FieldKey);
                        var options=[];
                        this.$.each(enums,function(i,item){
                            options.push({No:item.IntKey,Name:item.Lab})
                        });
                        this.searchForm.push( {type:'Select',label:condtion.Label,prop:condtion.FieldKey,width:"120px",options:options,props:{label:'Name',value:'No'}});
                        this.toolbarData[condtion.FieldKey]="";
                        break;
                    default:
                        var defVal = condtion.Val;
                        defVal = defVal.replace('<br/>', '');
                        defVal = defVal.replace('@Now', "(new Date())");
                        defVal = new Date(eval(defVal));
                        defVal = FormatDate(defVal, "yyyy-MM-dd");
                        this.searchForm.push({type:'Date',ctrlType:condtion.CtrlType, label: condtion.Label, prop:condtion.FieldKey, width:'120px'});
                        this.toolbarData[condtion.FieldKey]=defVal;

                        return;
                }
            },
            InitTableColumn(){
                var columns = this.mapExt.Tag;
                //显示列的中文名称.
                if (typeof columns == "string") {
                    columns.split(",").forEach(item=>{
                        var exp = item.split("=");
                        var field;
                        var title;
                        if (exp.length == 1) {
                            field = title = exp[0];
                        } else if (exp.length == 2) {
                            field = exp[0];
                            title = exp[1];
                        }
                        if (!this.isLegalName(field)) {
                            return true;
                        }
                        this.tableColumnData.push({
                            field: field,
                            text: title
                        });
                    });
                } else {
                    this.tableColumnData.push({
                        field:  'No',
                        text: '编号'
                    });
                    this.tableColumnData.push({
                        field:  'Name',
                        text: '名称'
                    });
                }
            },
            Search(){
                this.toolbarData.SearchKey = this.toolbarData.SearchKey.replace(/'/g,"");
                let dbSrc = this.mapExt.Tag2;
                dbSrc = dbSrc.replace(/~/g, "'");
                dbSrc = dbSrc.replace(/@Key/g, this.toolbarData.SearchKey);
                dbSrc = DealExp(dbSrc);
                let sqlWhere = "";
                let paras = "";
                paras += "@Key=" + this.toolbarData.SearchKey;
                this.searchForm.forEach(item=>{
                    var regC = new RegExp("@" + item.prop, "g");
                    dbSrc = dbSrc.replace(regC, this.toolbarData[item.prop]);
                    paras += "@" + item.prop + "=" + this.toolbarData[item.prop];
                    if (this.mapExt.DBType == 0) {

                        if (this.toolbarData[item.prop] != "") {
                            if (item.type.indexOf("Date") == -1) {
                                sqlWhere += " AND " + item.prop + "='" + this.toolbarData[item.prop] + "'";
                            } else {
                                if (item.ctrlType == "DateFrom")
                                    sqlWhere += " AND " + item.prop + ">='" + this.toolbarData[item.prop] + "'";
                                if (item.ctrlType == "DateTo") {
                                    var key = item.prop.replace("_DateTo", "");
                                    this.toolbarData[item.prop] = this.toolbarData[item.prop] + " 23:59";
                                    sqlWhere += " AND " + key + "<='" + this.toolbarData[item.prop] + "'";
                                }
                            }
                        }
                    }
                });
                let json=[];
                if (this.mapExt.DBType == 0) {
                    var en = new this.Entity("BP.Sys.MapExt",this.mapExt);
                    en.MyPK = this.mapExt.MyPK;
                    json = en.DoMethodReturnString("GetDataTableByField", "Tag2", paras, sqlWhere, this.params.WorkID+"");
                    if (json.indexOf("err@") != -1) {
                        this.$message.error(json);
                        console.log(json);
                        return;
                    }
                    json = JSON.parse(json);
                } else {
                    json = this.DBAccess.RunDBSrc(dbSrc); //执行url返回json.
                }
                this.tableData=json;
            },
            isLegalName(name) {
                if (!name) {
                    return false;
                }
                return name.match(/^[a-zA-Z\$_][a-zA-Z\d\$_]*$/);
            },
            ChangeToolbarData(val){
                this.toolbarData = val;
            },
            RowSelect(){

            },
            handleSelectionChange(val){
                if(this.selectType==false){
                    if (val.length > 1) {
                        this.$refs.table.clearSelection()
                        this.$refs.table.toggleRowSelection(val[val.length-1])
                    }/*else{
                        this.multipleSelection.push(val);
                    }*/

                }
                this.multipleSelection=this.$refs.table.store.states.selection;


            },
            currentChange(val){
                this.$refs.table.toggleRowSelection(val);
            }

        },
        watch: {
            multipleSelection(){
                this.$emit("on-selectRow-change",this.multipleSelection);
            },

        }
    }
</script>

<style scoped>

</style>